﻿using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using viBook.Common;
using viBook.Models;

namespace viBook.Controllers
{
    public class BaseController : Controller
    {
        protected readonly JsonResult _successFeedback;
        protected readonly JsonResult _failedFeedback;

        protected BaseController()
        {
            _successFeedback = Json(new { success = true });
            _failedFeedback = Json(new { success = false, message = Constant.ErrorMessage });
        }

        protected internal ExtendedIdentity ExtendedIdentity
        {
            get
            {
                return User.Identity as ExtendedIdentity;
            }
        }
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = SessionPersiter.User;
            filterContext.HttpContext.User = new ExtendedPrincipal(new ExtendedIdentity(user));
        }
    }
    public static class SessionPersiter
    {
        private const string UsernameSession = "user";

        public static User User
        {
            get
            {
                if (HttpContext.Current.Session == null)
                {
                    return null;
                }
                var sessionVal = HttpContext.Current.Session[UsernameSession];
                return sessionVal != null ? sessionVal as User : null;
            }
            set { HttpContext.Current.Session[UsernameSession] = value; }
        }
    }
}